package com.dferreira.languagesteach.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Display;
import android.view.WindowManager;

import com.dferreira.languagesteach.constants.Constants;

public class DeviceStretcher {
    private final Context context;
    private Matrix matrix;

    /**
     * Initializes the matrix that will stretch the images
     *
     * @param heightDevice Height from the current device
     */
    private void initializeMatrixTransformation(int heightDevice) {
        float zoom;

        zoom = (float) ((1.0 * heightDevice) / Constants.HEIGHT_DISPLAY_BASE);
        matrix = new Matrix();
        matrix.postScale(zoom, zoom);
    }

    /**
     * @return the width from the current device
     */
    private int getDisplayHeight() {
        WindowManager windowManager;
        Display display;
        windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        display = windowManager.getDefaultDisplay();
        //noinspection deprecation
        return display.getHeight();
    }


    public DeviceStretcher(Context context) {
        int heightDevice;

        this.context = context;
        heightDevice = getDisplayHeight();
        initializeMatrixTransformation(heightDevice);
    }

    /**
     * @param original original draw image
     * @return image stretched
     */
    public Drawable zoomDrawable(Drawable original) {
        Bitmap originalBitmap;
        Bitmap scaledBitmap;

        if (original == null) {
            return null;
        }
        originalBitmap = ((BitmapDrawable) original).getBitmap();

        scaledBitmap = Bitmap.createBitmap(originalBitmap, 0, 0, originalBitmap.getWidth(), originalBitmap.getHeight(), matrix, true);
        return new BitmapDrawable(context.getResources(), scaledBitmap);
    }
}
